import MSLogger; log = MSLogger.get('wsgi_server')
import MSUser
import threading
import os

def genUsers(path):
    if not os.path.exists(path): return
    for f in os.listdir(path):
        if f[0] == '.': continue
        if f.find('.user') == -1: continue

        name = f.split('.user')[0]
        obj = MSUser.MSUser(path, name)
        obj.open()
        if obj.storage.txn == 0: continue
        if obj.storage.meta.has_key('dont_load') and obj.storage.meta['dont_load'] == True: continue
        yield (obj.hash, obj)

class MSUsers:
    def __init__(self, path):
        self.path = path
        self.objs = {}
        self.lock = threading.Lock()

    def load(self):
        self.lock.acquire()
        try:
            log.debug('Users::load: ...')
            for oid,obj in genUsers(self.path):
                log.debug('loaded %s user(%s)', oid, obj.storage.meta['email'])
                self.objs[oid] = obj
            log.info('Users::load: done')
        finally:
            self.lock.release()

    def find(self, userId, Locked=False):
        if not Locked: self.lock.acquire()
        try:
            if self.objs.has_key(userId): return self.objs[userId]
            return None
        finally:
            if not Locked: self.lock.release()
